package com.khson.knows.portal.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.khson.knows.portal.mapper.TagMapper;
import com.khson.knows.portal.model.Tag;
import com.khson.knows.portal.service.ITagService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author com.khson
 * @since 2021-08-23
 */
@Service
public class TagServiceImpl extends ServiceImpl<TagMapper, Tag> implements ITagService {

    //声明一个List保存所有标签,用作缓存
    private List<Tag> tags = new CopyOnWriteArrayList<>();
    //声明一个Map保存所有标签,用户根据标签名获取对象
    private Map<String,Tag> tagMap = new ConcurrentHashMap<>();
    @Autowired
    private TagMapper tagMapper;

    @Override
    public List<Tag> getTags() {
        //判断tags属性是否空,如果表示空则当前查询是第一次查询
        //  1   2   3
        if(tags.isEmpty()){
            synchronized (tags) {   //防止多线程同时进入,同时查询
                if(tags.isEmpty()) {
                    List<Tag> list = tagMapper.selectList(null);
                    tags.addAll(list);
                    for (Tag tag : tags) {
                        tagMap.put(tag.getName(),tag);
                    }
                }
            }
        }
        return tags;
    }

    @Override
    public Map<String, Tag> getTagMap() {
        if(tagMap.isEmpty()){
            getTags();
        }
        return tagMap;
    }
}
